package cn.iocoder.yudao.module.im.convert.message;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.im.controller.app.message.vo.AppMessageRespVO;
import cn.iocoder.yudao.module.im.controller.app.message.vo.AppMessageSendRespVO;
import cn.iocoder.yudao.module.im.dal.dataobject.message.MessageDO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息 Convert
 *
 * @author 芋道源码
 */
@Mapper
public interface MessageConvert {

    MessageConvert INSTANCE = Mappers.getMapper(MessageConvert.class);

    @Mapping(source = "id", target = "msgId")
    @Mapping(source = "msgId", target = "id")
    @Mapping(source = "at", target = "at", qualifiedByName = "stringToLongList")
    @Mapping(source = "sendTime", target = "sendTime", qualifiedByName = "timestampToLocalDateTime")
    AppMessageSendRespVO convert(MessageDO bean);

    @Mapping(source = "at", target = "at", qualifiedByName = "stringToLongList")
    @Mapping(source = "extra", target = "extendData")
    AppMessageRespVO convertToAppMessageRespVO(MessageDO bean);

    List<AppMessageSendRespVO> convertList(List<MessageDO> list);
    
    List<AppMessageRespVO> convertToAppMessageRespVOList(List<MessageDO> list);

    /**
     * 将逗号分隔的字符串转换为Long列表
     */
    @Named("stringToLongList")
    default List<Long> stringToLongList(String atStr) {
        if (StrUtil.isBlank(atStr)) {
            return Collections.emptyList();
        }
        return Arrays.stream(atStr.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .map(Long::parseLong)
                .collect(Collectors.toList());
    }

    /**
     * 将时间戳转换为LocalDateTime
     */
    @Named("timestampToLocalDateTime")
    default LocalDateTime timestampToLocalDateTime(Long timestamp) {
        if (timestamp == null) {
            return null;
        }
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
    }

}